package cn.com.bluemoon.daps.system.utils;

import cn.com.bluemoon.daps.common.exception.DapException;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;

public class ImportCertificate {

    /**
     * 上传证书
     * @param file
     * @return
     */
    public static String upload(MultipartFile file){

        if(file != null){
            // 获取文件的名称
            String originalFilename = file.getOriginalFilename();
            // 文件后缀 例如：.png
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            if(!fileSuffix.equals(".pem")){
                throw new DapException("文件格式必须为pem,请重新上传！");
            }
        }
        //上传文件
        String string = file.getOriginalFilename(); //获取文件名，带后缀
        String substring = string.substring(0, string.lastIndexOf("."));// 不带后缀
        String fileName = substring + String.valueOf(new Date().getTime()/1000) + ".pem";
        String path = null;
        try {
            path = ResourceUtils.getURL("classpath:").getPath()+"certificate/";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        File folderPath = new File(path);
        if (!folderPath.exists() && !folderPath.isDirectory()){//查询文件夹是否存在
            folderPath.mkdir();//建立一级子目录
            System.out.println("目录不存在，创建新文件夹");
        }
        File filePath = new File(path + fileName);
        try{
            file.transferTo(filePath);//将上传的文件写到服务器上指定的文件路径
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
       return null;
    }

    /**
     * 下载证书
     * @param certificate
     */
    public static void downLoad(String certificate){



    }
}
